<template>
  <div class="dashboard-container">
    <div class="header">
      <h1>商品销售统计看板</h1>
    </div>

    <!-- 销售概览表格 -->
    <div class="panel">
      <div class="panel-title">商品销售概览</div>
      <div class="table-container">
        <el-table
            :data="salesOverviewData"
            border
            style="width: 100%"
            :header-cell-style="{
            background: '#f5f7fa',
            color: '#606266',
            fontWeight: 'bold'
          }"
        >
          <el-table-column prop="productName" label="商品名目" align="center" />
          <el-table-column prop="salesQuantity" label="销售数量" align="center" />
          <el-table-column prop="salesPercentage" label="销售占比" align="center" />
          <el-table-column prop="chainRatio" label="环比变化" align="center" />
          <el-table-column prop="salesAmount" label="销售金额" align="center" />
          <el-table-column prop="salesVolumePercentage" label="销售量占比" align="center" />
          <el-table-column prop="volumeChainRatio" label="环比变化" align="center" />
        </el-table>
      </div>
    </div>

    <!-- 销售额况 -->
    <div class="panel">
      <div class="panel-title">商品销售额况</div>

      <!-- 时间筛选 -->
      <div class="time-filter">
        <el-radio-group v-model="selectedTime" @change="handleTimeChange">
          <el-radio-button label="本月" />
          <el-radio-button label="本季度" />
          <el-radio-button label="本年" />
          <el-radio-button label="自定义日期" />
        </el-radio-group>

        <!-- 日期选择器 -->
        <div v-if="selectedTime === '自定义日期'" class="date-picker-container">
          <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
          />
        </div>
      </div>

      <!-- 商品类目筛选 -->
      <div class="category-filter">
        <div class="filter-title">商品类目：</div>
        <div class="category-tags">
          <el-tag
              v-for="category in productCategories"
              :key="category"
              :type="selectedCategory === category ? 'primary' : 'info'"
              class="category-tag"
              @click="selectCategory(category)"
          >
            {{ category }}
          </el-tag>
        </div>
      </div>

      <!-- 详细销售数据表格 -->
      <div class="table-container">
        <el-table
            :data="filteredProductSalesData"
            border
            style="width: 100%"
            :header-cell-style="{
            background: '#f5f7fa',
            color: '#606266',
            fontWeight: 'bold'
          }"
        >
          <el-table-column prop="productName" label="商品名称" align="center" />
          <el-table-column prop="productionVolume" label="制造量" align="center" />
          <el-table-column prop="consumerGroup" label="消费人群" align="center" />
          <el-table-column prop="paymentGroup" label="付款人群" align="center" />
          <el-table-column prop="conversionRate" label="单品转化率" align="center" />
          <el-table-column prop="salesQuantity" label="销售数量" align="center" />
          <el-table-column prop="salesAmount" label="销售金额" align="center" />
        </el-table>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <div class="chart-card">
        <div class="chart-title">商品销售占比分析</div>
        <div class="chart-container" ref="salesPercentageChart"></div>
      </div>

      <div class="chart-card">
        <div class="chart-title">环比变化趋势</div>
        <div class="chart-container" ref="chainRatioChart"></div>
      </div>
    </div>

    <div class="footer">
      <p>来源：艾瑞咨询</p>
      <p>©2022Q3全球领先企业，国内领先企业。数据仅供参考</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import * as echarts from 'echarts'

// 图表引用
const salesPercentageChart = ref(null)
const chainRatioChart = ref(null)
let salesPercentageChartInstance = null
let chainRatioChartInstance = null

// 销售概览数据
const salesOverviewData = ref([
  {
    productName: '陆前赚取',
    salesQuantity: 3134,
    salesPercentage: '214.9%',
    chainRatio: 13.21,
    salesAmount: 'WB0501.23',
    salesVolumePercentage: '214.9%',
    volumeChainRatio: 13.21
  },
  {
    productName: '大牌专区',
    salesQuantity: 2953,
    salesPercentage: '19.26%',
    chainRatio: 13.23,
    salesAmount: 'WB0716.39',
    salesVolumePercentage: '19.26%',
    volumeChainRatio: 13.23
  },
  {
    productName: '智能手表',
    salesQuantity: 2789,
    salesPercentage: '17.53%',
    chainRatio: 11.23,
    salesAmount: 'WF24001.30',
    salesVolumePercentage: '17.53%',
    volumeChainRatio: 11.23
  },
  {
    productName: '智能秤',
    salesQuantity: 2247,
    salesPercentage: '11.45%',
    chainRatio: 10.26,
    salesAmount: 'WB0718.09',
    salesVolumePercentage: '11.45%',
    volumeChainRatio: 10.26
  },
  {
    productName: '睡眠管理',
    salesQuantity: 2247,
    salesPercentage: '11.45%',
    chainRatio: 13.23,
    salesAmount: 'WB0718.09',
    salesVolumePercentage: '11.45%',
    volumeChainRatio: 13.23
  },
  {
    productName: '营养健康',
    salesQuantity: 1357,
    salesPercentage: '6.21%',
    chainRatio: 12.08,
    salesAmount: 'WBF001.28',
    salesVolumePercentage: '6.21%',
    volumeChainRatio: 12.08
  },
  {
    productName: '护理清洁',
    salesQuantity: 1407,
    salesPercentage: '6.38%',
    chainRatio: 11.25,
    salesAmount: 'WB07165.08',
    salesVolumePercentage: '6.38%',
    volumeChainRatio: 11.25
  },
  {
    productName: '智能手表',
    salesQuantity: 1499,
    salesPercentage: '7.56%',
    chainRatio: 10.17,
    salesAmount: 'WF19001.62',
    salesVolumePercentage: '7.56%',
    volumeChainRatio: 10.17
  },
  {
    productName: '血压计',
    salesQuantity: 1678,
    salesPercentage: '9.32%',
    chainRatio: 10.36,
    salesAmount: 'WB17151.39',
    salesVolumePercentage: '9.32%',
    volumeChainRatio: 10.36
  },
  {
    productName: '运动户外',
    salesQuantity: 1597,
    salesPercentage: '8.20%',
    chainRatio: 11.21,
    salesAmount: 'WF9101.23',
    salesVolumePercentage: '8.20%',
    volumeChainRatio: 11.21
  }
])

// 时间筛选
const selectedTime = ref('本月')
const dateRange = ref([])

// 商品类目筛选
const productCategories = ref([
  '陆前赚取', '大牌专区', '智能手表', '智能秤', '睡眠管理',
  '营养健康', '护理清洁', '血压计', '运动户外'
])
const selectedCategory = ref('陆前赚取')

// 商品销售详细数据
const productSalesData = ref([
  {
    productName: '小米手码',
    productionVolume: 2000,
    consumerGroup: 700,
    paymentGroup: 60,
    conversionRate: '10%',
    salesQuantity: 120,
    salesAmount: '¥1200000',
    category: '智能手表'
  },
  {
    productName: '华为手表',
    productionVolume: 1800,
    consumerGroup: 650,
    paymentGroup: 55,
    conversionRate: '12%',
    salesQuantity: 150,
    salesAmount: '¥1500000',
    category: '智能手表'
  },
  {
    productName: '苹果手表',
    productionVolume: 1500,
    consumerGroup: 500,
    paymentGroup: 45,
    conversionRate: '15%',
    salesQuantity: 180,
    salesAmount: '¥1800000',
    category: '智能手表'
  },
  {
    productName: '智能体脂秤',
    productionVolume: 2200,
    consumerGroup: 800,
    paymentGroup: 70,
    conversionRate: '8%',
    salesQuantity: 90,
    salesAmount: '¥900000',
    category: '智能秤'
  },
  {
    productName: '智能手环',
    productionVolume: 2500,
    consumerGroup: 900,
    paymentGroup: 80,
    conversionRate: '9%',
    salesQuantity: 100,
    salesAmount: '¥1000000',
    category: '智能手表'
  },
  {
    productName: '睡眠监测仪',
    productionVolume: 1200,
    consumerGroup: 400,
    paymentGroup: 35,
    conversionRate: '11%',
    salesQuantity: 75,
    salesAmount: '¥750000',
    category: '睡眠管理'
  },
  {
    productName: '血压监测仪',
    productionVolume: 1300,
    consumerGroup: 450,
    paymentGroup: 40,
    conversionRate: '13%',
    salesQuantity: 85,
    salesAmount: '¥850000',
    category: '血压计'
  }
])

// 计算属性：根据筛选条件过滤数据
const filteredProductSalesData = computed(() => {
  if (selectedCategory.value === '全部') {
    return productSalesData.value
  }
  return productSalesData.value.filter(item => item.category === selectedCategory.value)
})

// 时间筛选处理
const handleTimeChange = (value) => {
  console.log('时间筛选:', value)
  if (value !== '自定义日期') {
    dateRange.value = []
  }
  updateCharts()
}

// 日期选择处理
const handleDateChange = (dates) => {
  if (dates && dates.length === 2) {
    console.log('选择的日期范围:', dates[0], '至', dates[1])
    updateCharts()
  }
}

// 商品类目筛选
const selectCategory = (category) => {
  selectedCategory.value = category
  updateCharts()
}

// 初始化销售占比图表
const initSalesPercentageChart = () => {
  if (!salesPercentageChart.value) return

  salesPercentageChartInstance = echarts.init(salesPercentageChart.value)

  // 过滤掉陆前赚取，因为它的占比太大影响图表显示
  const chartData = salesOverviewData.value
      .filter(item => item.productName !== '陆前赚取')
      .map(item => ({
        name: item.productName,
        value: parseFloat(item.salesPercentage)
      }))

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}%'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center'
    },
    series: [
      {
        name: '销售占比',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: chartData
      }
    ]
  }

  salesPercentageChartInstance.setOption(option)
}

// 初始化环比变化图表
const initChainRatioChart = () => {
  if (!chainRatioChart.value) return

  chainRatioChartInstance = echarts.init(chainRatioChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['环比变化']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: salesOverviewData.value.map(item => item.productName)
    },
    yAxis: {
      type: 'value',
      name: '百分比变化'
    },
    series: [
      {
        name: '环比变化',
        type: 'bar',
        data: salesOverviewData.value.map(item => item.chainRatio),
        itemStyle: {
          color: function(params) {
            const colorList = [
              '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
              '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'
            ]
            return colorList[params.dataIndex % colorList.length]
          }
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}%'
        }
      }
    ]
  }

  chainRatioChartInstance.setOption(option)
}

// 更新图表
const updateCharts = () => {
  if (salesPercentageChartInstance) {
    salesPercentageChartInstance.dispose()
    initSalesPercentageChart()
  }
  if (chainRatioChartInstance) {
    chainRatioChartInstance.dispose()
    initChainRatioChart()
  }
}

const handleResize = () => {
  if (salesPercentageChartInstance) {
    salesPercentageChartInstance.resize()
  }
  if (chainRatioChartInstance) {
    chainRatioChartInstance.resize()
  }
}

onMounted(() => {
  nextTick(() => {
    initSalesPercentageChart()
    initChainRatioChart()
  })

  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)

  if (salesPercentageChartInstance) {
    salesPercentageChartInstance.dispose()
  }
  if (chainRatioChartInstance) {
    chainRatioChartInstance.dispose()
  }
})
</script>

<style scoped>
.dashboard-container {
  max-width: 1400px;
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.header {
  text-align: center;
  margin-bottom: 24px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 16px;
}

.header h1 {
  color: #303133;
  font-size: 24px;
  font-weight: 500;
}

.panel {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 16px;
  margin-bottom: 24px;
}

.panel-title {
  font-size: 18px;
  color: #303133;
  margin-bottom: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.panel-title::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.time-filter {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.date-picker-container {
  margin-left: 16px;
}

.category-filter {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.filter-title {
  font-size: 14px;
  color: #606266;
  margin-right: 12px;
  white-space: nowrap;
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.category-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.category-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.chart-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 16px;
  height: 400px;
}

.chart-title {
  font-size: 16px;
  color: #303133;
  margin-bottom: 16px;
  text-align: center;
  font-weight: 500;
}

.chart-container {
  width: 100%;
  height: 340px;
}

.footer {
  text-align: center;
  margin-top: 32px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
  color: #909399;
  font-size: 14px;
}

@media (max-width: 1024px) {
  .charts-container {
    grid-template-columns: 1fr;
  }

  .category-filter {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-title {
    margin-bottom: 8px;
  }

  .time-filter {
    flex-direction: column;
    align-items: flex-start;
  }

  .date-picker-container {
    margin-left: 0;
    margin-top: 8px;
  }
}
</style>